import { login, register, logout } from '@/api/user/index.js'
import {
  getToken,
  setToken,
  removeToken,
  getRoles,
  setRoles,
  removeRoles,
} from '@/utils/cookie'
const user = {
  state: {
    token: getToken(),
    roles: getRoles(),
    // promissions: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
  },

  actions: {
    // 登陆
    LOGIN({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data)
          .then((res) => {
            console.log(res)
            setToken(res.data.token)
            setRoles(res.data.authority)
            commit('SET_TOKEN', res.data.token)
            commit('SET_ROLES', res.data.authority)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 注册
    REGISTER({ commit }, data) {
      return new Promise((resolve, reject) => {
        register(data)
          .then((res) => {
            // setToken(res.token)
            resolve()
          })
          .catch(() => {
            reject()
          })
      })
    },
    // 退出登陆
    LOGOUT({ commit }, data) {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            console.debug(res)
            removeToken()
            removeRoles()
            commit('SET_TOKEN', '')
            commit('SET_ROLES', '')
            resolve()
          })
          .catch(() => {
            reject()
          })
      })
    },
    // 清除无效token
    CLEARTOKEN({ commit }, data) {
      return new Promise((resolve, reject) => {
        removeToken()
        removeRoles()
        commit('SET_TOKEN', '')
        commit('SET_ROLES', '')
        resolve()
      }).catch(() => {
        reject()
      })
    },
  },
}
export default user
